package com.fanhang.samples.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TalkServer {

	public static void main(String args[]) {
		try {
			ServerSocket server = null;
			try {
				server = new ServerSocket(9999);
			} catch (Exception e) {
				System.out.println("can not listen to:" + e);
			}
			Socket socket = null;
			try {
				socket = server.accept();
				// 使用accept()阻塞等待客户请求，有客户请求到来则产生一个Socket对象，并继续执行
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			// 输入：来自client
			BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 输出：到往client
			PrintWriter os = new PrintWriter(socket.getOutputStream());

			String input = is.readLine();
			System.out.println("Client:" + input);
			
			int index = " bye quit exit ".indexOf(" " + input + " ");
			while (index == -1) {
				os.printf("Your message is:[%s]%n", input);
				os.flush();
				
				input = is.readLine();
				System.out.println("Client:" + input);
				index = " bye quit exit ".indexOf(" " + input + " ");
			}
			
			os.print("bye\n");
			
			os.close();
			is.close();
			socket.close();
			server.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
